package com.liu.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Created by shi860715@126.com
 * Date 2021/8/11 10:48
 * 安全配置
 */
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(securedEnabled=true,prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  PasswordEncoder passwordEncoder;

  @Autowired
  UserDetailsService userDetailsService;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
//         配置放行页面面，不需要权限验证
        http.authorizeRequests().antMatchers("/home").permitAll()
//                配置其他页面都需要登录才能访问
                .anyRequest().authenticated()
                 .and()
//                配置登录页放行
                .formLogin().permitAll()
                .and()
//                退出页面放行
                .logout().permitAll()
                .and()
//               配置允许跨域
                .cors()
                .and()
//                关闭csrf
                .csrf().disable();

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//       使用数据库的方式，做安全验证
     auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
//        内存中配置用户
//        auth.inMemoryAuthentication()
////                添加用户test01 并享有admin user test 三种角色  自动会加上ROLE_
//                .withUser("test01").password(passwordEncoder.encode("123456")).roles("admin","user")
//                .and()
////                添加用户test02 user test 权限 还是以前的字符串
//                .withUser("test02").password(passwordEncoder.encode("123456")).authorities("user:add","user:edit","test")
//                .and().
//                withUser("test03").password(passwordEncoder.encode("123456")).authorities("user:add","user:edit","test").roles("admin","user","test");
    }
}
